<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="520px"
    top="0"
    :before-close="cancelBtn"
    :close-on-click-modal="false"
    @open="open"
  >
    <el-form
      v-if="type==1"
      ref="formRef"
      :model="ruleForm"
      :rules="formRules"
      label-position="top"
    >
      <el-form-item label="邀请码名称" prop="name">
        <el-input v-model.trim="ruleForm.name" placeholder="请输入20字以内的名称"></el-input>
      </el-form-item>
      <el-form-item label="减免金额(元)" prop="reduction">
        <el-input
          v-model.trim="ruleForm.reduction"
          placeholder="请输入减免金额(元)"
          @input="onInputValue"
        ></el-input>
      </el-form-item>
      <el-form-item label="邀请码数量" prop="num">
        <el-input
          v-model.trim="ruleForm.num" min="0" max="10000"
          placeholder="请输入1-1w之间的数字"
          @input="inputValue"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirm">立即添加</el-button>
      </el-form-item>
    </el-form>
    <el-form
      v-if="type==2"
      ref="formRef2"
      :model="ruleForm"
      :rules="formRules2"
      label-position="top"
    >
      <el-form-item label="邀请码名称" prop="name">
        <el-select v-model.trim="ruleForm.name" placeholder="选择要追加的邀请码名称">
          <el-option
            v-for="(item, index) in codeNamesOptions"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邀请码数量" prop="num">
        <el-input
          v-model.trim="ruleForm.num" min="0" max="10000"
          placeholder="请输入1-1w之间的数字"
          @input="inputValue"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirm">立即添加</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  import {AddInvite, AppendInvite, GetInviteQuery} from "@/api/campSystem/campOper";

  export default {
    name: "AddInviteCode",
    props: {
      dialogVisibleFu: Boolean,
      typeFu: [String, Number],
    },
    data() {
      // 邀请码数量正则
      const checkReduction = (rule, value, callback) => {
        const reg = /^[1-9]\d{0,3}$|^10000$/;
        if (!value) {
          callback(new Error('请输入邀请码数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入1-1w之间的数字'));
        } else {
          callback();
        }
      };
      return {
        dialogVisible: this.dialogVisibleFu,
        ruleForm: {
          campsiteId: null,
          name: null,
          num: null,
          reduction: null,
        },
        formRules: {
          name: [
            {required: true, message: '请输入邀请码名称', trigger: 'blur'},
            {max: 20, message: '请输入20字以内的名称', trigger: 'blur'}
          ],
          reduction: [
            {required: true, message: '请输入减免金额', trigger: 'blur'}
          ],
          num: [
            {required: true, validator: checkReduction, trigger: 'blur'}
          ],
        },
        formRules2: {
          name: [
            {required: true, message: '请选择邀请码名称', trigger: 'blur'},
          ],
          num: [
            {required: true, validator: checkReduction, trigger: 'blur'}
          ],
        },
        isChecked: false, // 防重复点击
        type: 1, // 类型 1-添加邀请码，2-追加邀请码
        title: '添加邀请码',
        codeNamesOptions: []// 邀请码列表
      };
    },
    methods: {
      open() {
        this.ruleForm.campsiteId = this.$route.query.id;
        if (this.typeFu == 2) {
          this.title = '追加邀请码';
          this.getInviteQuery();
        } else {
          this.title = '添加邀请码';
        }
      },
      confirm() {
        if (this.isChecked) {
          return;
        }
        this.isChecked = true;
        if (this.type == 1) {
          this.$refs['formRef'].validate((valid) => {
            if (!valid) {
              this.isChecked = false;
              return;
            }

            AddInvite(this.ruleForm)
              .then(response => {
                console.log(response);
                if (response.code != 200) {
                  this.isChecked = false;
                  return this.msgError(response.msg);
                }
                this.isChecked = false;
                this.msgSuccess(response.msg)
                this.$refs['formRef'].resetFields();
                this.ruleForm = {
                  campsiteId: null,
                  name: null,
                  num: null,
                  reduction: null,
                };
                this.dialogVisible = false;
                this.$emit("closeDialog", this.dialogVisible, true);
              })
              .catch(error => {
                console.log(error);
                this.isChecked = false;
              });
          });
        } else if (this.type == 2) {
          this.$refs['formRef2'].validate((valid) => {
            if (!valid) {
              this.isChecked = false;
              return;
            }
            this.ruleForm.reduction = 0;
            AppendInvite(this.ruleForm)
              .then(response => {
                console.log(response);
                if (response.code != 200) {
                  this.isChecked = false;
                  return this.msgError(response.msg);
                }
                this.isChecked = false;
                this.msgSuccess(response.msg)
                this.$refs['formRef2'].resetFields();
                this.ruleForm = {
                  campsiteId: null,
                  name: null,
                  num: null,
                  reduction: null,
                };
                this.dialogVisible = false;
                this.$emit("closeDialog", this.dialogVisible, true);
              })
              .catch(error => {
                console.log(error);
                this.isChecked = false;
              });
          });
        }
      },
      // 取消,关闭弹框，修改父组件的值
      cancelBtn() {
        this.ruleForm = {
          campsiteId: null,
          name: null,
          num: null,
          reduction: null,
        };
        this.dialogVisible = false;
        this.$emit("closeDialog", this.dialogVisible, false);
      },
      inputValue(value) {
        if (value.length > 1 && value.slice(0, 1) == 0) {
          return this.ruleForm.num = 0;
        }
        this.ruleForm.num = value.replace(/[^\d]/g, '');
      },
      onInputValue(value) {
        if (value.length > 1 && value.slice(0, 1) == 0) {
          return this.ruleForm.reduction = 0;
        }
        this.ruleForm.reduction = value.replace(/[^\d]/g, '');
      },
      // 获取指定营地邀请码筛选列表
      getInviteQuery() {
        GetInviteQuery({
          campsiteId: this.ruleForm.campsiteId
        })
          .then(response => {
            console.log(response);
            if (response.code != 200) {
              return this.msgError(response.msg);
            }
            this.codeNamesOptions = response.data;
          })
          .catch(error => {
            console.log(error);
          });
      },
    },
    watch: {
      dialogVisibleFu() {
        this.dialogVisible = this.dialogVisibleFu;
      },
      typeFu() {
        this.type = this.typeFu;
      },
    },
  };
</script>

<style scoped lang="scss">
  ::v-deep .el-form-item__content {
    text-align: center;

    .el-select {
      width: 100%;
    }
  }
</style>

